package com.hxd.otc.module.convenience.activity;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.base.OnItemClickListener;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.ConvenienceBusinessTypeEnum;
import com.hxd.otc.module.convenience.adapter.VideoGoodsAdapter;
import com.hxd.otc.module.convenience.adapter.VideoTypeAdapter;
import com.hxd.otc.module.convenience.bean.NorGoodsBean;
import com.hxd.otc.module.convenience.bean.OrderInfoBean;
import com.hxd.otc.module.convenience.bean.RefuelingServiceBean;
import com.hxd.otc.module.convenience.contract.VideoServiceRechargeContract;
import com.hxd.otc.module.convenience.fragment.ConvenienceFragment;
import com.hxd.otc.module.convenience.fragment.PayDialogFragment;
import com.hxd.otc.module.convenience.presenter.VideoServiceRechargePresenter;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.AutoSplitOnTvGlobalLayoutAdapter;
import com.hxd.otc.widget.TextWatcherAdapter;
import com.hxd.otc.widget.TitleBar;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by lzy on 2018/12/14 0014.
 * description ${视频服务充值}
 */
public class VideoServiceRechargeActivity extends BaseActivity<VideoServiceRechargePresenter> implements VideoServiceRechargeContract.IView {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.recyclerView_video)
    RecyclerView mRecyclerViewVideo;
    @BindView(R.id.et_account)
    EditText mEtAccount;
    @BindView(R.id.recyclerView_goods)
    RecyclerView mRecyclerViewGoods;
    @BindView(R.id.tv_account_require)
    TextView mTvAccountRequire;

    private VideoTypeAdapter mVideoTypeAdapter;
    private VideoGoodsAdapter mVideoGoodsAdapter;
    private PayDialogFragment mPayDialogFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_service_recharge;
    }

    @Override
    protected VideoServiceRechargePresenter createPresenter() {
        return new VideoServiceRechargePresenter(this);
    }

    @Override
    protected void initView() {
        mRecyclerViewVideo.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        mVideoTypeAdapter = new VideoTypeAdapter(this);
        mRecyclerViewVideo.setAdapter(mVideoTypeAdapter);

        mRecyclerViewGoods.setLayoutManager(new GridLayoutManager(this, 3));
        mVideoGoodsAdapter = new VideoGoodsAdapter(this);
        mRecyclerViewGoods.setAdapter(mVideoGoodsAdapter);
    }

    @Override
    protected void initData() {
        Bundle bundle = getBundle();
        if (bundle != null) {
            mPresenter.setRefuelingServiceBean((RefuelingServiceBean) bundle.getSerializable(ConvenienceFragment.EXTRA_REFUELING_SERVICE_BEAN));
            mPresenter.setBusinessType((ConvenienceBusinessTypeEnum) bundle.getSerializable(ConvenienceFragment.EXTRA_BUSINESS_TYPE));
        }
        mPresenter.getVideoTypeData();
    }

    @Override
    protected void initEvent() {
        mVideoTypeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                updateSelVideoType(mVideoTypeAdapter.getItem(position));
            }
        });
        mVideoGoodsAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                onSelGoods(mVideoGoodsAdapter.getItem(position));
            }
        });
        mEtAccount.addTextChangedListener(mAccountWatcher);
        mTvAccountRequire.getViewTreeObserver().addOnGlobalLayoutListener(new AutoSplitOnTvGlobalLayoutAdapter(mTvAccountRequire));
    }

    private TextWatcherAdapter mAccountWatcher = new TextWatcherAdapter() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mEtAccount.removeTextChangedListener(mAccountWatcher);
            String phoneNumber = s.toString().trim().replace(" ", "");
            if (DataUtils.isPhoneNumberNotHit(phoneNumber)) {
                mVideoGoodsAdapter.setEnable(true);
            } else {
                mVideoGoodsAdapter.setEnable(false);
            }
            String newPhoneNumber = formatPhone(phoneNumber);
            mEtAccount.setText(newPhoneNumber);
            mEtAccount.setSelection(newPhoneNumber.length());
            mEtAccount.addTextChangedListener(mAccountWatcher);
        }
    };

    private String formatPhone(String phoneNumber) {
        if (phoneNumber.length() < 3) return phoneNumber;
        char[] chars = phoneNumber.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            sb.append(chars[i]).append(i == 2 || i == 6 ? " " : "");
        }
        return sb.toString().trim();
    }

    /**
     * 商品选择
     */
    private void onSelGoods(NorGoodsBean item) {
        if (!UserHelper.isLogin()) {
            Bundle bundle = new Bundle();
            bundle.putBoolean(LoginActivity.EXTRA_FINISH_SKIP_MAIN, false);
            $startActivity(LoginActivity.class, bundle);
            return;
        }

        String videoAccount = mEtAccount.getText().toString().replace(" ", "").trim();
        if (TextUtils.isEmpty(videoAccount)) {
            showToast(getString(R.string.please_enter_your_video_account));
            return;
        }
        OrderInfoBean videoServiceRechargeOrder = OrderInfoBean.createVideoServiceRecharge
                (videoAccount, item, mPresenter.getBusinessType(),mTitleBar.getTitle().getText().toString(),item.getPriceUnit());
        if (mPayDialogFragment == null) {
            mPayDialogFragment = PayDialogFragment.getInstance();
        } else {
            UIUtils.dismissDialogFragment(mPayDialogFragment);
        }
        mPayDialogFragment.setData(videoServiceRechargeOrder);
        mPayDialogFragment.show(getSupportFragmentManager(), getClass().getSimpleName());

    }

    private void updateSelVideoType(RefuelingServiceBean item) {
        if (item == null) return;
        mVideoTypeAdapter.setSelItem(item);
        mPresenter.getVideoGoodsData(item.getId());
        mVideoGoodsAdapter.clear();
    }

    @Override
    public void getVideoTypeDataSuccess(ArrayList<RefuelingServiceBean> refuelingServiceBeans) {
        mVideoTypeAdapter.addAll(true, refuelingServiceBeans);
        if (refuelingServiceBeans == null) return;
        int size = refuelingServiceBeans.size();
        mRecyclerViewVideo.setLayoutManager(size > 4 ? new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false) : new GridLayoutManager(this, size <= 3 ? 3 : 4));
        updateSelVideoType(refuelingServiceBeans.size() > 0 ? refuelingServiceBeans.get(0) : null);
    }

    @Override
    public void getVideoGoodsDataSuccess(String moduleId, ArrayList<NorGoodsBean> norGoodsBeans) {
        RefuelingServiceBean selItem = mVideoTypeAdapter.getSelItem();
        if (selItem == null) return;
        //判断当前返回的商品数据是否属于当前视频平台，如果不是则需要重新获取商品信息
        if (moduleId.equals(selItem.getId())) {
            mVideoGoodsAdapter.addAll(true, norGoodsBeans);
        } else {
            mPresenter.getVideoGoodsData(selItem.getId());
        }
    }

    @Override
    public void getVideoGoodsDataFail(String moduleId, String errMessage) {
        showToast(errMessage);
    }
}
